package com.hmall.item.service.impl;

import cn.hutool.core.bean.BeanUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.DeleteRequest;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import com.hmall.api.domain.po.Item;
import com.hmall.item.domain.dto.ItemDoc;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
@RequiredArgsConstructor
public class ItemDocService {

    private final ElasticsearchClient elasticsearchClient;

    /**
     * 新增或更新商品文档到Elasticsearch
     */
    public void saveItemDoc(Item item) {
        try {
            ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
            IndexRequest<ItemDoc> request = IndexRequest.of(i -> i
                    .index("items")
                    .id(itemDoc.getId().toString())
                    .document(itemDoc)
            );
            elasticsearchClient.index(request);
            log.info("商品文档同步成功，商品ID: {}", item.getId());
        } catch (IOException e) {
            log.error("商品文档同步失败，商品ID: {}", item.getId(), e);
        }
    }

    /**
     * 从Elasticsearch删除商品文档
     */
    public void deleteItemDoc(Long itemId) {
        try {
            DeleteRequest request = DeleteRequest.of(d -> d
                    .index("items")
                    .id(itemId.toString())
            );
            elasticsearchClient.delete(request);
            log.info("商品文档删除成功，商品ID: {}", itemId);
        } catch (IOException e) {
            log.error("商品文档删除失败，商品ID: {}", itemId, e);
        }
    }
}
